<?php

namespace Acme\DemoBundle\Controller;

use Acme\DemoBundle\Entity\TMusic;

use Symfony\Component\HttpFoundation\Response;

use Symfony\Component\Validator\Constraints\DateTime;

use Acme\DemoBundle\Entity\RChat;

use Doctrine\ORM\Query\Expr\Math;

use Symfony\Component\HttpFoundation\File\File;

use Symfony\Component\Validator\Constraints\Image;

use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer;

use Acme\DemoBundle\Entity\RAlbumImage;

use Acme\DemoBundle\Entity\TImage;

use Acme\DemoBundle\Entity\TAlbum;

use Symfony\Component\Security\Core\SecurityContext;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class HomeController extends Controller
{
    public function indexAction()
    {
        $aryNewAlbumList = self::getNewAlbum();
// var_dump($aryNewAlbumList);die;
        $aryNewImageList = self::getNewImage();
        $aryMusicList = self::getAryMusicList();
        return $this->render('AcmeDemoBundle:Home:index.html.twig', array(
                                        'aryNewImageList' => $aryNewImageList,
                                        'aryMusicList' => $aryMusicList,
                                        'aryNewAlbumList' => $aryNewAlbumList,
                            ));
    }

    /**
     * load new image
     * @return ary
     */
    public function getNewImage()
    {
        $objManager = $this->getDoctrine()->getManager();
        try {
            $strSQL = " Select * From t_image Where is_deleted = false ";
            $strSQL .= " Order by id desc Limit 6 ";
            $statement = $objManager->getConnection()->prepare($strSQL);
            $statement->execute();
            $results = $statement->fetchAll();
            return $results;

        } catch (Exception $e) {
            $objManager->getConnection()->rollback();
            var_dump($e);die;
        }

    }

    /**
     * load new album
     * @return ary
     */
    public function getNewAlbum()
    {
        $aryResultList = array();
        $objManager = $this->getDoctrine()->getManager();
        try {
            $aryAlbumList = $this->getDoctrine()->getEntityManager()
                ->createQueryBuilder()
                // not use: select c.*, use: select c
                ->select('r.t_album_id, a.title')
                ->from('AcmeDemoBundle:RAlbumImage', 'r')

                ->leftJoin('AcmeDemoBundle:TAlbum', 'a', ' WITH ', 'r.t_album_id = a.id and a.is_deleted = false')

                ->orderBy('r.t_album_id', 'DESC')

                ->setMaxResults(2)

                ->distinct(true)

                ->getQuery()
                ->getResult();

            if($aryAlbumList){
                foreach($aryAlbumList as $key => $aryAlbum){
                    $aryResultList[$key]['t_album_id'] = $aryAlbum['t_album_id'];
                    $aryResultList[$key]['title'] = $aryAlbum['title'];
                    $aryResultList[$key]['image_list'] = $this->getDoctrine()->getEntityManager()
                        ->createQueryBuilder()
                        // not use: select c.*, use: select c
                        ->select('r.t_image_id, i.name, i.note, i.image_path')
                        ->from('AcmeDemoBundle:RAlbumImage', 'r')

                        ->leftJoin('AcmeDemoBundle:TAlbum', 'a', ' WITH ', 'r.t_album_id = a.id and a.is_deleted = false')
                        ->leftJoin('AcmeDemoBundle:TImage', 'i', ' WITH ', 'r.t_image_id = i.id and i.is_deleted = false')

                        ->where('r.t_album_id = :album_id')
                        ->setParameter('album_id', $aryAlbum['t_album_id'])

                        ->orderBy('r.t_image_id', 'ASC')

                        ->setMaxResults(100)

                        ->getQuery()
                        ->getResult();
                }
            }

//             return $this->getDoctrine()->getEntityManager()
//             ->createQueryBuilder()
//             // not use: select c.*, use: select c
//             ->select('r.t_album_id, r.t_image_id, a.title, i.name, i.note, i.image_path')
//             ->from('AcmeDemoBundle:RAlbumImage', 'r')

//             ->leftJoin('AcmeDemoBundle:TAlbum', 'a', ' WITH ', 'r.t_album_id = a.id and a.is_deleted = false')
//             ->leftJoin('AcmeDemoBundle:TImage', 'i', ' WITH ', 'r.t_image_id = i.id and i.is_deleted = false')

//             ->groupBy('r.t_album_id, r.t_image_id, a.title, i.name, i.note, i.image_path')
//             ->orderBy('r.t_album_id', 'DESC')

//             ->setMaxResults(100)

//             ->getQuery()
//             ->getResult();

            return $aryResultList;

        } catch (Exception $e) {
            $objManager->getConnection()->rollback();
            var_dump($e);die;
        }

    }

    /**
     * Action save upload file
     *
     */
    public function uploadFileAction()
    {
        $request = $this->get('request');

        if ($request->isMethod('POST')) {
            $strTile = '';
            $intMainImageId = '';
            $strName = '';
            $strNote = '';
            $intUploadType = $request->request->get('hidUploadType');
            $intCount = $request->request->get('hidUploadCount');

            // Set time limit to indefinite execution
            set_time_limit (0);

            /**
             * if: image
             * else: music
             */
            if($intUploadType != '3') {
                // just save in database
                $strDBPath = $this->container->getParameter('my_memory_image_db_path');
                // path to save image
                $strSavePath = __DIR__ . "/../../../../web/" . $strDBPath;
                $strMiniSavePath = $strSavePath . "mini/";

                // set directory
                if ( !is_dir( $strSavePath ) ) {
                    mkdir($strSavePath, 0777, true);
                    chmod($strSavePath, 0777 );
                }

                if ( !is_dir( $strMiniSavePath ) ) {
                    mkdir($strMiniSavePath, 0777, true);
                    chmod($strMiniSavePath, 0777 );
                }

            } else {
                // just save in database
                $strDBPath = $this->container->getParameter('my_memory_music_db_path');
                // path to save image
                $strSavePath = __DIR__ . "/../../../../web/" . $strDBPath;

                // set directory
                if ( !is_dir( $strSavePath ) ) {
                    mkdir($strSavePath, 0777, true);
                    chmod($strSavePath, 0777 );
                }
            }

            $objManager = $this->getDoctrine()->getManager();
            try {

                $objManager->getConnection()->beginTransaction();

                if($intUploadType == '1') {
                    $strTile = $request->request->get('txtTitle');
                    $intAlbumId = self::saveAlbum($objManager, $strTile);
                    $intFirstImageId = null;
                    for($i = 0; $i <= $intCount; $i++) {
                        if($_FILES['fileUpload_' . $i]) {
                            // get path
                            $aryImagePath = pathinfo($_FILES['fileUpload_' . $i]['name']);
                            // set tmp name
                            $strFileNameTemp = time() . "." . $aryImagePath["extension"];

                            if(move_uploaded_file($_FILES['fileUpload_' . $i]['tmp_name'], $strSavePath . $strFileNameTemp)) {
                                self::resizeImage($strSavePath . $strFileNameTemp, 800, 800, $strSavePath . $strFileNameTemp);

                                copy($strSavePath . $strFileNameTemp, $strMiniSavePath . $strFileNameTemp);
                                self::resizeImage($strMiniSavePath . $strFileNameTemp, 152, 152, $strMiniSavePath . $strFileNameTemp, true);

                                $strName = $strFileNameTemp;
                                $strNote = $request->request->get('txtNote_' . $i);

                                $intImageId = self::saveImage($objManager, $strName, $strNote, $strDBPath);
                                self::saveRAlbumImage($objManager, $intAlbumId, $intImageId);

                                if($i == 0) {
                                    $intFirstImageId = $intImageId;
                                }
                            }
                        }
                    }

                    $objAlbum2 = $objManager->getRepository('AcmeDemoBundle:TAlbum')->find($intAlbumId);
                    $objAlbum2->setTMainImageId($intFirstImageId);
                    $objManager->persist($objAlbum2);
                    $objManager->flush();

                } elseif($intUploadType == '2') {
                    // get path
                    $aryImagePath = pathinfo($_FILES['fileUpload']['name']);
                    // set tmp name
                    $strFileNameTemp = time() . "." . $aryImagePath["extension"];

                    if(move_uploaded_file($_FILES['fileUpload']['tmp_name'], $strSavePath . $strFileNameTemp)) {
                        self::resizeImage($strSavePath . $strFileNameTemp, 800, 800, $strSavePath . $strFileNameTemp);

                        copy($strSavePath . $strFileNameTemp, $strMiniSavePath . $strFileNameTemp);
                        self::resizeImage($strMiniSavePath . $strFileNameTemp, 152, 152, $strMiniSavePath . $strFileNameTemp, true);

                        $strName = $strFileNameTemp;
                        $strNote = $request->request->get('txtNote');

                        $intImageId = self::saveImage($objManager, $strName, $strNote, $strDBPath);
                    }

                } elseif($intUploadType == '3') {
                    for($i = 0; $i <= $intCount; $i++) {
                        if($_FILES['fileUpload_' . $i]) {

                            // set tmp name
                            $strName = $_FILES['fileUpload_' . $i]['name'];

                            if(move_uploaded_file($_FILES['fileUpload_' . $i]['tmp_name'], $strSavePath . $strName)) {
                                self::saveMusic($objManager, $strName, 1, null, null, null, $strDBPath, null);
                            }
                        }
                    }
                }

                $objManager->getConnection()->commit();

            } catch (Exception $e) {
                $objManager->getConnection()->rollback();
                var_dump($e);die;
            }
        }

        return $this->redirect($this->generateUrl("_home"));

    }

    public function resizeImage($filename, $newwidth, $newheight, $newfilename, $sameSize = false)
    {
        header('Content-type: image/jpeg');
        list($width, $height) = getimagesize($filename);
        if(!$sameSize) {
            if($width > $height && $newheight < $height){
                $newheight = $height / ($width / $newwidth);
            } else if ($width < $height && $newwidth < $width) {
                $newwidth = $width / ($height / $newheight);
            } else {
                $newwidth = $width;
                $newheight = $height;
            }
        }
        $thumb = imagecreatetruecolor($newwidth, $newheight);
        $source = imagecreatefromjpeg($filename);
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

        imagejpeg($thumb, $newfilename);
        imagedestroy($source);
        imagedestroy($thumb);

        return true;
    }

    public function resizeImage2($file, $filename, $newwidth = 800, $newheight = 600)
    {
        $type = substr($file,strrpos($file,".")+1);

        switch($type)
        {
            case 'jpg':
                $src = imagecreatefromjpeg($file);
                break;
            case 'jpeg':
                $src = imagecreatefromjpeg($file);
                break;
            case 'gif':
                $src = imagecreatefromgif($file);
                break;
            case 'png':
                $src = imagecreatefrompng($file);
                break;
            default:
                $src = imagecreatefromjpeg($file);
                break;
        }

        list($width,$height)=getimagesize($file);
        $tmp=imagecreatetruecolor($newwidth,$newheight);
        imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

        switch($type) {
            case 'jpg':
                imagejpeg($tmp,$filename,100);
                break;
            case 'jpeg':
                imagejpeg($tmp,$filename,100);
                break;
            case 'gif':
                imagegif($tmp,$filename,100);
                break;
            case 'png':
                imagepng($tmp,$filename,9);
                break;
            case 'wbm':
                imagewbmp($tmp,$filename,100);
                break;
            default:
                imagejpeg($tmp,$filename,100);
                break;
        }
        imagedestroy($src);
        imagedestroy($tmp);
        return true;
    }

    /**
     * save Image
     */
    public function saveImage($objManager, $strName, $strNote, $strPath)
    {
        $objImage = new TImage();
        $objImage->setName($strName);
        $objImage->setNote($strNote);
        $objImage->setImagePath($strPath);
        $objImage->setCreateAt(new \DateTime("now"));
        $objImage->setCreateUserId($this->get('session')->get('user_id'));
        $objImage->setUpdateAt(new \DateTime("now"));
        $objImage->setUpdateUserId($this->get('session')->get('user_id'));
        $objImage->setIsDeleted(0);

        $objManager->persist($objImage);
        $objManager->flush();

        return $objImage->getId();
    }

    /**
     * save Album
     */
    public function saveAlbum($objManager, $strTile, $intMainImageId = null)
    {
        $objAlbum = new TAlbum();
        $objAlbum->setTitle($strTile);
        $objAlbum->setTMainImageId($intMainImageId);
        $objAlbum->setCreateAt(new \DateTime("now"));
        $objAlbum->setCreateUserId($this->get('session')->get('user_id'));
        $objAlbum->setUpdateAt(new \DateTime("now"));
        $objAlbum->setUpdateUserId($this->get('session')->get('user_id'));
        $objAlbum->setIsDeleted(0);

        $objManager->persist($objAlbum);
        $objManager->flush();

        return $objAlbum->getId();
    }

    /**
     * save r_album_image
     */
    public function saveRAlbumImage($objManager, $intAlbumId, $intImageId)
    {
        $objRAlbumImage = new RAlbumImage();
        $objRAlbumImage->setTAlbumId($intAlbumId);
        $objRAlbumImage->setTImageId($intImageId);

        $objManager->persist($objRAlbumImage);
        $objManager->flush();
    }

    /**
     * send msg Action
     *
     */
    public function sendMessageAction()
    {
        $request = $this->get('request');

        if ($request->isMethod('POST')) {
            $objManager = $this->getDoctrine()->getManager();
            try {
                $objManager->getConnection()->beginTransaction();

                $intSendUserId = $this->get('session')->get('user_id');
                $intReceivedUserId = $intSendUserId == 1 ? 2 : 1;
                $strMsg = $request->request->get('txtSendMsg');
                self::saveRChat($objManager, $intSendUserId, $intReceivedUserId, $strMsg);

                $objManager->getConnection()->commit();

            } catch (Exception $e) {
                $objManager->getConnection()->rollback();
                var_dump($e);die;
            }
        }


        // use Symfony\Component\HttpFoundation\Response;
        $response = new Response();
        $response->headers->set('Content-Type', 'text/plain');
        $response->setContent($strMsg);

        return $response;

    }

    /**
     * send msg Action
     *
     */
    public function getMessageAction()
    {
        //exec("php /my/project/app/console cache:clear");
        //self::cacheClear();
        $aryChatList = self::getAryChatList();
        return $this->render('AcmeDemoBundle:Home:getChat.html.twig.twig', array(
                                        'aryChatList' => $aryChatList
                            ));
    }

    public function cacheClear() {
        $input = new \Symfony\Component\Console\Input\ArgvInput(array('console','cache:clear'));
        $application = new \Symfony\Bundle\FrameworkBundle\Console\Application($this->get('kernel'));
        $application->run($input);
    }

    /**
     * save chat
     */
    public function saveRChat($objManager, $intSendUserId, $intReceivedUserId, $strMsg)
    {

        $objRChat = new RChat();
        $objRChat->setSendUserId($intSendUserId);
        $objRChat->setReceivedUserId($intReceivedUserId);
        $objRChat->setMessage($strMsg);
        $objRChat->setSendAt(new \DateTime("now"));

        $objManager->persist($objRChat);
        $objManager->flush();
    }

    /**
     * get chat
     * @return ary
     */
    public function getAryChatList()
    {
        $objManager = $this->getDoctrine()->getManager();
        try {
            // option 1
//             $strSQL = " Select * From r_chat ";
//             $strSQL .= " Where send_user_id = 1 and received_user_id = 2  ";
//             $statement = $objManager->getConnection()->prepare($strSQL);
//             $statement->execute();
//             $results = $statement->fetchAll();
//             return $results;

            // option 2
            return $this->getDoctrine()->getEntityManager()
            ->createQueryBuilder()
            // not use: select c.*, use: select c
            ->select('c.message, c.send_at, c.send_user_id, c.received_user_id, u1.user_name as send_user_name, u2.user_name as received_user_name')
            ->from('AcmeDemoBundle:RChat', 'c')

            ->leftJoin('AcmeDemoBundle:TUser', 'u1', ' WITH ', 'c.send_user_id = u1.id')
            ->leftJoin('AcmeDemoBundle:TUser', 'u2', ' WITH ', 'c.received_user_id = u2.id')

            ->where('c.send_user_id in (:user_id)')
            ->setParameter('user_id', array(1,2))

            ->orderBy('c.send_at', 'ASC')

            ->setMaxResults(100)

            ->getQuery()
            ->getResult();

        } catch (Exception $e) {
            var_dump($e);die;
        }
    }
    /**
     * save music
     */
    public function saveMusic($objManager, $strName, $intMusicType = 1, $strSingler = null,
                            $strAuthor = null, $strLyric = null, $strPath, $intListenNo = 0)
    {
        $objData = new TMusic();
        $objData->setName($strName);
        $objData->setMMusicTypeId($intMusicType);
        $objData->setSinger($strSingler);
        $objData->setAuthor($strAuthor);
        $objData->setLyric($strLyric);
        $objData->setPath($strPath);
        $objData->setListenedNo($intListenNo);
        $objData->setCreateAt(new \DateTime("now"));
        $objData->setCreateUserId($this->get('session')->get('user_id'));
        $objData->setUpdateAt(new \DateTime("now"));
        $objData->setUpdateUserId($this->get('session')->get('user_id'));
        $objData->setIsDeleted(0);

        $objManager->persist($objData);
        $objManager->flush();

        return $objData->getId();
    }

    /**
     * get music
     * @return ary
     */
    public function getAryMusicList()
    {
        $objManager = $this->getDoctrine()->getManager();
        try {
            return $this->getDoctrine()->getEntityManager()
            ->createQueryBuilder()
            ->select('m.name, m.path')
            ->from('AcmeDemoBundle:TMusic', 'm')

            ->where('m.is_deleted = 0')

            ->orderBy('m.id', 'DESC')

            ->setMaxResults(10)

            ->getQuery()
            ->getResult();

        } catch (Exception $e) {
            var_dump($e);die;
        }
    }
}
